package com.atm.bulksms;

import java.util.Vector;

import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioGroup;

import com.atm.bulksms.data.ContactItem;
import com.atm.bulksms.util.Utils;
public class NumberListDialog extends Dialog{
	RadioGroup group;
	int contactId = 0;
	Vector<String> selectedNumber;
	String selectedName = "";
	public NumberListDialog(final ContactChooser parent,String title, String[] items, int id) {
		super(parent);
		setTitle(title);
		this.contactId = id;
		setContentView(R.layout.number_list);
		group = (RadioGroup)findViewById(R.id.phone_number_group);
		
		
		//updateGroup(parent, items, id);
		Button doneBtn = (Button)findViewById(R.id.btn_done);
		doneBtn.setOnClickListener(new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				boolean checked = false;
				for (int i = 0; i < group.getChildCount(); i++) {
					CheckBox cb = (CheckBox)group.getChildAt(i);
					if(checked = cb.isChecked())break;
				}
				if(!checked){
					System.out.println(" list item should be marked unchecked");
					Utils.removeContact(contactId);
					parent.toggleView(false);
				}else{
					ContactItem item = new ContactItem(selectedName, selectedNumber);
					Utils.addContact(contactId, item);
					parent.toggleView(true);
				}
				System.out.println("On DIalog Done :: "+Utils.getSelectedContacts());
				cancel();
			}
			});
	}
	public void updateGroup(Context context, String name, String[] items, int id) {
		this.contactId = id;
		group.removeAllViews();
		selectedNumber = new Vector<String>();
		selectedName = name;
		ContactItem item = Utils.getContactItem(id);
		Vector<String> existingContacts = item != null ? item.getNumberList() : null;
		for (int i = 0; i < items.length; i++) {
			CheckBox check = new CheckBox(context);	
			check.setText(items[i]);
			if(existingContacts != null && existingContacts.contains(items[i])){
				check.setChecked(true);
				if(!selectedNumber.contains(items[i])) selectedNumber.add(items[i]);
			}
			check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
				@Override
				public void onCheckedChanged(CompoundButton buttonView,
						boolean isChecked) {
					System.out.println("buttonView "+buttonView.getText()+" isChecked :: "+isChecked);
					if(isChecked)
						selectedNumber.add(buttonView.getText().toString());
					else
						selectedNumber.remove(buttonView.getText().toString());
				}
				
			});
			group.addView(check);
		}
	}
	
	
	
	

}
